/*
 * @lc app=leetcode.cn id=566 lang=javascript
 *
 * [566] 重塑矩阵
 */

// @lc code=start
/**
 * @param {number[][]} mat
 * @param {number} r
 * @param {number} c
 * @return {number[][]}
 */
//  思想：
//  就是把mat扁平化后赋值给res
//  找到索引间的对应关系可以将空间复杂度降低
// https://leetcode-cn.com/problems/reshape-the-matrix/solution/zhong-su-ju-zhen-by-leetcode-solution-gt0g/

//  复杂度：O(nm) O(mn)

var matrixReshape = function (mat, r, c) {
    if (mat.length === 0) return mat
    const row = mat.length, col = mat[0].length
    if (row * col === r * c) {
        let res = Array.from(new Array(r), () => new Array(c).fill(0))
        let count = 0, copy = mat.flat()
        for (let i = 0; i < r; i++) {
            for (let j = 0; j < c; j++) {
                res[i][j] = copy[count++]
            }
        }
        return res
    } else {
        return mat
    }
};
// @lc code=end

console.log(matrixReshape([[1, 2], [3, 4]], 1, 4));